<template>
  <div class="tinymce-editor">
    <editor
      v-if="!reloading"
      v-model="myValue"
      :init="init"
      :disabled="disabled"
      @onClick="onClick">
    </editor>
  </div>
</template>

<script>

  import tinymce from 'tinymce/tinymce'
  import Editor from '@tinymce/tinymce-vue'
  import 'tinymce/themes/silver/theme'
  import 'tinymce/plugins/image'
  import 'tinymce/plugins/link'
  import 'tinymce/plugins/media'
  import 'tinymce/plugins/table'
  import 'tinymce/plugins/lists'
  import 'tinymce/plugins/contextmenu'
  import 'tinymce/plugins/wordcount'
  import 'tinymce/plugins/colorpicker'
  import 'tinymce/plugins/textcolor'
  import 'tinymce/plugins/fullscreen'
  import 'tinymce/icons/default'
  import { uploadAction, getFileAccessHttpUrl } from '@/api/manage'
  import YchConstant from "@/api/YchConstant";
  import store from '../../store'

  const vue_app_locale = store.getters.language;

  export default {
    name: 'YchEditor',
    components: {
      Editor
    },
    props: {
      value: String,
      disabled: Boolean,
      plugins: {
        type: [String, Array],
        default: 'lists image link media table textcolor wordcount contextmenu fullscreen'
      },
      toolbar: {
        type: [String, Array],
        default: 'undo redo |  formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists link unlink image media table | removeformat | fullscreen',
        branding: false
      },
      height:{
        type:Number,
        default:300,
        require:false
      }
    },
    data() {
      return {
        //初始化配置
        init: {
          language_url: `/tinymce/langs/${vue_app_locale}.js`,
          language: vue_app_locale,
          skin_url: '/tinymce/skins/lightgray',
          height: this.height,
          plugins: this.plugins,
          toolbar: this.toolbar,
          branding: false,
          menubar: false,
          toolbar_drawer: false,
          images_upload_handler: (blobInfo, success) => {

            let formData = new FormData()
            formData.append('file', blobInfo.blob(), blobInfo.filename());
            formData.append('biz', "YchEditor");
            formData.append("YchEditor", "1");
            uploadAction(bootConfig[process.env.NODE_ENV].VUE_APP_API + YchConstant.PREFIX_SYSTEM + "/common/upload", formData).then((res) => {
              if (res.success) {
                let img = getFileAccessHttpUrl(res.message)
                success(img)
              }
            })

          }
        },
        myValue: this.value,
        reloading: false,
      }
    },
    mounted() {
      this.initATabsChangeAutoReload()
    },
    methods: {
      reload() {
        this.reloading = true
        this.$nextTick(() => this.reloading = false)
      },
      onClick(e) {
        this.$emit('onClick', e, tinymce)
      },
      clear() {
        this.myValue = ''
      },

      /**
       * 自动判断父级是否是 <a-tabs/> 组件，然后添加事件监听，自动触发reload()
       *
       * 由于 tabs 组件切换会导致 tinymce 无法输入，
       * 只有重新加载才能使用（无论是vue版的还是jQuery版tinymce都有这个通病）
       */
      initATabsChangeAutoReload() {
        // 获取父级
        let tabs = getVmParentByName(this, 'ATabs')
        let tabPane = getVmParentByName(this, 'ATabPane')
        let tabLayout = getVmParentByName(this, 'TabLayout')
        if (tabs && tabPane) {
          // 用户自定义的 key
          let currentKey = tabPane.$vnode.key
          // 添加事件监听
          tabs.$on('change', (key) => {
            // 切换到自己时执行reload
            if (currentKey === key) {
              this.reload()
            }
          })
          this.reload()
        } else if (tabLayout && tabLayout.excuteCallback) {
          tabLayout.excuteCallback(() => {
            this.reload()
          })
        } else {
          this.reload()
        }
      },
    },
    watch: {
      value(newValue) {
        this.myValue = newValue || ''
      },
      myValue(newValue) {
        this.$emit('change', newValue)
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    },
  }

  /**
   * 根据组件名获取父级
   * @param vm
   * @param name
   * @returns {Vue | null|null|Vue}
   */
  function getVmParentByName(vm, name) {
    let parent = vm.$parent
    if (parent && parent.$options) {
      if (parent.$options.name === name) {
        return parent
      } else {
        let res = getVmParentByName(parent, name)
        if (res) {
          return res
        }
      }
    }
    return null
  }
</script>
